import React, { Component } from "react";
import { withRouter} from 'react-router-dom'
import { Card, Form, Input, Cascader, Upload, Button, message } from "antd";

import { ArrowLeftOutlined } from "@ant-design/icons";
import LinkButton from "../../components/link-button";
import { reqCategorys,reqAddOrUpdateProduct } from "../../api";

import PicturesWall from './pictures-wall'
import  RichTextEditor  from './rich-text-editor'
const { Item } = Form;
const { TextArea } = Input;
// @withRouter
class AddUpdate extends Component {
  formRef = React.createRef();
  state = {
    options: [],
    parentId: 0,
  };

  constructor ( props ) { 
    super( props )
    this.pw = React.createRef()
    this.rte=React.createRef()
  }
  initOptions = async (categorys) => {
    const options = categorys.map((c) => ({
      value: c._id,
      label: c.name,
      isLeaf: false,
    }));
    //如果是一个二级分类商品的更新
    const { isUpdate, product } = this
    const { pCategoryId, categoryId } = product
    if ( isUpdate && pCategoryId !== 0 ) { 
      const subCategorys = await this.getCategorys( categoryId )
      //生成二级下拉列表
      const childOptions=subCategorys.map((c) => ({
        value: c._id,
        label: c.name,
        isLeaf: true,
	  } ) )
		console.log(pCategoryId);
		const targetOption = options.find( option => option.value === pCategoryId )
		console.log(targetOption);
    //   targetOption.children=childOptions
    }
    this.setState({
      options: options,
    });
  };
  //得到分类列表
  getCategorys = async (parentId) => {
    const res = await reqCategorys(parentId);
    // console.log(res);
    if (res.data.status === 0) {
      const categorys = res.data.data;
      // console.log(parentId);
      if (parentId === 0) {
        this.initOptions(categorys);
      } else {
        return categorys; //返回二级列表
      }
    }
    // console.log(res);
    // this.initOptions()
  };
  componentDidMount() {
    this.getCategorys(0);
  }
  //提交验证
  submit = () => {
    //进行表单验证
    this.formRef.current
      .validateFields()
      .then(async(values) => {
        // console.log( this.pw.current.getImgs() )
        // console.log( this.rte.current.getDetail() );
        // console.log(values);
        //收集数据，并封装成promise对象

        const { name, desc,  categorysIds } = values
        const price=values.price*1
        let pCategoryId,categoryId
        if ( categorysIds.length === 1 ) {
          pCategoryId = '0';
          categoryId = categorysIds[ 0 ];
        } else { 
          pCategoryId = categorysIds[ 0 ]
          categoryId = categorysIds[ 1 ]
        }
        // console.log(name);
        console.log(price);
        const imgs = JSON.stringify(this.pw.current.getImgs())
        console.log(imgs);
        const detail = this.rte.current.getDetail()
        const product = { name, desc, price, imgs, detail,pCategoryId,categoryId }
        console.log(product);
        if ( this.isUpdate ) { 
          product._id=this.product._id
        }
        //添加商品发送ajax
        const res = await reqAddOrUpdateProduct(product)
        // console.log(res);
        if ( res.data.status === 0 ) {
          message.success( '添加商品成功' );
        }
        else { 
          message.error('添加商品失败')
        }
      })
      .catch((err) => {
        // console.log("err");
      });
  };

  //用于加载下一级列表的回调函数
  loadData = async (selectedOptions) => {
    const targetOption = selectedOptions[selectedOptions.length - 1];
    targetOption.loading = true;
    //根据选中的分类请求显示下一级列表
    const subCategorys = await this.getCategorys(targetOption.value);
    targetOption.loading = false;
    if (subCategorys && subCategorys.length > 0) {
      const childOptions = subCategorys.map((c) => ({
        value: c._id,
        label: c.name,
        isLeaf: true,
      }));
      targetOption.children = childOptions;
    } else {
      targetOption.isLeaf = true;
    }

    this.setState({
      options: [...this.state.options],
    });
    // setOptions([...options]);
  };
  componentWillMount() {
    const product = this.props.location.state;
    // console.log(this.props.location);
    //保存一个是否更新的标识
    console.log(!!product);
    this.isUpdate = !!product;
    this.product = product || {};
  }
  render() {
    const { isUpdate, product } = this;
    const { pCategoryId, categoryId, imgs, detail } = product;
    const title = (
      <span>
        <LinkButton>
          <ArrowLeftOutlined onClick={ ()=>this.props.history.goBack(-1)} style={{ fontSize: 20 }} />
        </LinkButton>
        <span>{isUpdate ? "修改商品" : "添加商品"}</span>
      </span>
    );
    //指定item布局的配置对象
    const layout = {
      labelCol: {
        span: 2,
      },
      wrapperCol: {
        span: 8,
      },
    };
    // console.log(this.props.Form);
    // 用来接收级联分类的数组
    const categorysIds = [];
    if (isUpdate) {
      if (pCategoryId === 0) {
        categorysIds.push(pCategoryId);
      } else {
        categorysIds.push(pCategoryId);
        categorysIds.push(categoryId);
      }
    }
    return (
      <div>
        <Card title={title}>
          <Form ref={this.formRef} {...layout}>
            <Item
              rules={[{ required: true, message: "商品名称不能为空" }]}
              name="name"
              label="商品名称"
            >
              <Input initialValue={product.name} placeholder="商品名称" />
            </Item>
            <Item
              rules={[{ required: true, message: "商品描述不能为空" }]}
              name="desc"
              label="商品描述"
            >
              <TextArea
                initialValue={product.desc}
                placeholder="请输入商品描述"
                rows={2}
              />
            </Item>
            <Item
              rules={[
                { required: true, message: "商品价格不能为空" },
                ({ getFieldValue }) => ({
                  validator(rule, value) {
                    // console.log(value);
                    if (value * 1 > 0) {
                      return Promise.resolve();
                    }

                    return Promise.reject("价格必须大于0");
                  },
                }),
              ]}
              name="price"
              label="商品价格"
            >
              <Input
                initialValue={product.price}
                type="number"
                placeholder="请输入商品价格"
                addonAfter="元"
              />
            </Item>
            <Item name="categorysIds" label="商品分类">
              <Cascader
                initialValue={categorysIds}
                options={this.state.options} //需要显示的列表数据
                loadData={this.loadData} //当选择某个列表项，加载下一个列表数据
              />
            </Item>
            <Item name="pic" label="商品图片">
              <PicturesWall ref={ this.pw } imgs={imgs}/>
            </Item>
					<Item name="detail" label="商品详情" labelCol={ { span: 2 } } wrapperCol={ {span:20}}>
              <RichTextEditor ref={ this.rte } detail={detail}/>
            </Item>
            <Item>
              <Button onClick={this.submit} type="primary">
                提交
              </Button>
            </Item>
          </Form>
        </Card>
      </div>
    );
  }
}

export default AddUpdate;
